# -*- coding: utf-8 -*-
import os
import streamlit as st
import tushare as ts
import pandas as pd
import talib
import numpy as np
import plotly.graph_objects as go
from tenacity import retry, stop_after_attempt, wait_fixed

st.title("主动渲染测试")
st.write("<script>console.log('前端脚本已加载')</script>", unsafe_allow_html=True)

# 初始化Tushare（通过环境变量或Streamlit secrets获取token）
try:
    ts.set_token(st.secrets["TUSHARE_TOKEN"])  # 必需在Streamlit后台配置secrets
except KeyError:
    st.error("❌ 请正确配置TUSHARE_TOKEN（通过Streamlit Secrets管理）")
    st.stop()
pro = ts.pro_api()

# 页面配置
st.set_page_config(page_title="AI股票盯盘助手", layout="wide", page_icon="📈")
st.title("📊 智能股票盯盘助手 v2.0")

# --------------------------
# 数据预处理模块
# --------------------------
@st.cache_data(ttl=3600)
def get_stock_list():
    """获取全量股票列表并缓存"""
    df = pro.stock_basic(exchange='', list_status='L')
    return df[['ts_code', 'name', 'industry']]

@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))
@st.cache_data(ttl=300, show_spinner="正在获取实时行情...")
def fetch_stock_data(code):
    """带重试机制的数据获取函数"""
    try:
        today_str = pd.Timestamp.today().strftime('%Y%m%d')
        
        # 尝试获取当日数据（交易时段）
        df = pro.daily(ts_code=code, start_date=today_str)
        
        # 如果当日无数据（盘前或非交易日），获取最近30日
        if df.empty:
            df = pro.daily(ts_code=code, end_date=today_str, limit=30)
        
        # 数据有效性校验
        if df.empty:
            raise ValueError("无有效交易数据")
            
        # 日期格式处理
        df['trade_date'] = pd.to_datetime(df['trade_date'], format='%Y%m%d')
        df = df.sort_values('trade_date').tail(30)  # 永远返回最近30个交易日
        
        # 计算技术指标
        df['MA5'] = talib.MA(df['close'], timeperiod=5)
        df['MA20'] = talib.MA(df['close'], timeperiod=20)
        df['MACD'], df['MACD_SIGNAL'], _ = talib.MACD(df['close'])
        
        # 计算资金流（价差×成交量）
        df['money_flow'] = (df['close'] - df['open']) * df['vol']
        
        return df
        
    except Exception as e:
        st.error(f"数据获取失败: {str(e)}")
        return pd.DataFrame()

# --------------------------
# 界面组件模块
# --------------------------
def build_sidebar():
    """侧边栏控件"""
    with st.sidebar:
        st.header("⚙️ 监控设置")
        
        # 股票代码选择（带搜索的下拉框）
        stock_list = get_stock_list()
        selected_code = st.selectbox(
            "选择监控股票",
            options=stock_list['ts_code'],
            format_func=lambda x: f"{x} ({stock_list[stock_list.ts_code == x]['name'].values[0]})",
            index=stock_list[stock_list.ts_code == '600519.SH'].index[0]
        )
        
        # 风险参数设置
        st.subheader("风险参数")
        alert_vol = st.slider("📉 波动率警报(%)", 1.0, 10.0, 3.0, 0.5)
        vol_multiplier = st.slider("📈 成交量放大倍数", 1.0, 5.0, 2.0, 0.5)
        
        # 系统状态显示
        st.divider()
        st.markdown("**系统状态** 🟢 运行正常")
        
        return selected_code, alert_vol, vol_multiplier

def plot_candlestick(data):
    """绘制交互式K线图"""
    fig = go.Figure(data=[
        go.Candlestick(
            x=data['trade_date'],
            open=data['open'],
            high=data['high'],
            low=data['low'],
            close=data['close'],
            name='K线'
        ),
        go.Scatter(
            x=data['trade_date'],
            y=data['MA5'],
            line=dict(color='orange', width=1.5),
            name='5日均线'
        ),
        go.Scatter(
            x=data['trade_date'],
            y=data['MA20'],
            line=dict(color='purple', width=1.5),
            name='20日均线'
        )
    ])
    
    fig.update_layout(
        title=f"{stock_code} 价格走势",
        xaxis_rangeslider_visible=False,
        hovermode="x unified",
        height=600
    )
    return fig

# --------------------------
# 分析逻辑模块
# --------------------------
def analyze_signals(data, vol_threshold, vol_multiplier):
    """生成交易信号"""
    if data.empty:
        return {}
    
    latest = data.iloc[-1]
    signals = {
        'volatility_alert': False,
        'capital_inflow': False,
        'macd_cross': False
    }
    
    # 波动率警报
    signals['volatility_alert'] = abs(latest['pct_chg']) > vol_threshold
    
    # 主力资金进场（量价齐升）
    mean_vol = data['vol'].iloc[:-1].mean()  # 计算历史平均成交量（排除最新数据）
    if (latest['vol'] > mean_vol * vol_multiplier and 
        latest['close'] > latest['open'] and
        data['money_flow'].iloc[-3:].mean() > data['money_flow'].mean() * 1.5):
        signals['capital_inflow'] = True
    
    # MACD金叉判断
    if (latest['MACD'] > latest['MACD_SIGNAL'] and 
        data.iloc[-2]['MACD'] <= data.iloc[-2]['MACD_SIGNAL']):
        signals['macd_cross'] = True
    
    return signals

# --------------------------
# 主程序流程
# --------------------------
if __name__ == "__main__":
    # 界面布局初始化
    stock_code, alert_vol, vol_multiplier = build_sidebar()
    data = fetch_stock_data(stock_code)
    
    if not data.empty:
        # --- 主显示区域 ---
        col_chart, col_status = st.columns([3, 1])
        
        with col_chart:
            # 交互式K线图
            st.plotly_chart(plot_candlestick(data), use_container_width=True)
            
            # 历史数据表格
            st.subheader("📜 近期交易数据")
            st.dataframe(
                data[['trade_date', 'open', 'close', 'high', 'low', 'vol']]
                .tail(10)
                .sort_values('trade_date', ascending=False)
                .style.format({
                    'open': '{:.2f}', 'close': '{:.2f}',
                    'high': '{:.2f}', 'low': '{:.2f}',
                    'vol': '{:,.0f}'
                }),
                height=400
            )
        
        with col_status:
            # 实时警报面板
            st.subheader("🔔 实时监控状态")
            signals = analyze_signals(data, alert_vol, vol_multiplier)
            
            # 显示仪表盘
            with st.container(border=True):
                st.metric("最新收盘价", 
                         f"¥{data.iloc[-1]['close']:.2f}", 
                         f"{data.iloc[-1]['pct_chg']:.2f}%")
                st.metric("当日成交量", 
                         f"{data.iloc[-1]['vol']/10000:,.1f} 万手", 
                         f"{data.iloc[-1]['vol']/data['vol'].mean():.1f}倍均量")
            
            # 信号通知区域
            with st.container():
                if signals['volatility_alert']:
                    st.error(f"⚠️ 价格剧烈波动！波动率: {abs(data.iloc[-1]['pct_chg']):.2f}%")
                if signals['capital_inflow']:
                    st.success("🚀 检测到主力资金进场信号！（量价齐升+资金流入）")
                if signals['macd_cross']:
                    st.info("💹 MACD金叉形态确认！潜在趋势反转信号")
                
    else:
        st.warning("⚠️ 未找到有效交易数据，请确认股票代码是否正确或稍后重试")
